#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/13
# @Author :songtx
# @File   :i2c.py


import time
import numpy as np
from smbus import SMBus


def i2c():
    bus = SMBus(1)  # 创建接口
    # level_high = 200  # 高液位报警限值
    # level_low = 50  # 低液位报警限值
    # list1, list2, list3, list4 = [], [], [], []  # 创建4个空list
    list1, list2 = [], []
    for i in range(5):  # 初始化，预读n组数据
        data1 = bus.read_word_data(0x40, 0x00)
        list1.append(data1)
        data2 = bus.read_word_data(0x41, 0x00)
        list2.append(data2)
        # data3 = bus.read_word_data(0x42, 0x00)
        # list3.append(data3)
        # data4 = bus.read_word_data(0x43, 0x00)
        # list4.append(data4)
        time.sleep(0.1)
    # 初始化和日常判断分开执行，初始化一次，循环判断
    while True:  # 循环最左插入1个值，最右删除1个值
        data1 = bus.read_word_data(0x40, 0x00)
        data2 = bus.read_word_data(0x41, 0x00)
        # data3 = bus.read_word_data(0x42, 0x00)
        # data4 = bus.read_word_data(0x43, 0x00)
        list1.insert(0, data1)
        list1.pop()
        list2.insert(0, data2)
        list2.pop()
        # list3.insert(0, data3)
        # list3.pop()
        # list4.insert(0, data4)
        # list4.pop()
        average1 = round(sum(list1) / len(list1))  # 平均值四舍五入
        average2 = round(sum(list2) / len(list2))
        # average3 = round(sum(list3) / len(list3))
        # average4 = round(sum(list4) / len(list4))

        data_now1 = round(sum(list1[0:2]) / 2)  # 前两组数据作为当前值
        data_now2 = round(sum(list2[0:2]) / 2)
        # data_now3 = round(sum(list3[0:2]) / 2)
        # data_now4 = round(sum(list4[0:2]) / 2)
        # list5 = [average1, average2, average3, average4]  # 4个平均值
        # list6 = [data_now1, data_now2, data_now3, data_now4]  # 4个当前值

        list5 = [average1, average2]  # 2个平均值
        list6 = [data_now1, data_now2]  # 2个当前值
        list7 = ['一号', '二号', '三号', '四号']  # 4个名称

        array1 = np.zeros(20).reshape(4, 5)
        # for i in range(4):  # 高低报警
        #     if list5[i] > level_high:
        #         array1[i - 1, 1] = 1
        #         # print(list7[i], '液位高')
        #     if list5[i] < level_low:
        #         array1[i - 1, 2] = 1
        # #         print(list7[i], '液位低')

        for i in range(2):  # 4个上升下降判断
            # if list6[i] - list5[i] > 3:
            #     array1[i - 1, 3] = 1
            #     # print(list7[i], '液位上升')
            # elif list6[i] - list5[i] < -3:
            #     array1[i - 1, 4] = 1
            #     # print(list7[i], '液位下降')
            # else:
            array1[i - 1, 0] = list5[i]
            # print(list7[i], '液位无变化，当前的液位是', list5[i])
        # print(array1)
        time.sleep(2)
        return array1
        # return time1, data0, data1, data2, data3


# i2c()
